/**
 * 事件通知
 */
export default class XTE {
    private handles = {};

    private static instance : XTE = null;

    public static get() : XTE  {
        if(this.instance) {
            return this.instance;
        }
        this.instance = new XTE();
        return this.instance;
    }

    private constructor() {

    }

    public on(type, handle){
        if(!type || !handle) return;
        if(!this.handles[type]){
            this.handles[type]=[]
        }
        this.handles[type].push(handle)
    }

    public emit(... args){
        if(args.length<=1){
            console.log("请输入发送的事件");
        }

        var type = Array.prototype.shift.call(args);
        if(!type || !this.handles[type]){
            console.log("错误: " + type + "还未在注册监听");
            return;
        }
        for(var i　=　0;　i　<　this.handles[type].length;　i++){
            this.handles[type][i].apply(this,　args);
        }
    }

    public off(type, ...handle){
        if(!this.handles[type] || !type) return;
        
        if(this.handles[type] && (!handle || handle.length <= 0)){
            
            for(let i = 0; i < this.handles[type].length; i ++) {
                console.log('i', i)
                delete this.handles[type][i];
            }
            delete this.handles[type];
            return
        }

        for(let j = 0; j < handle.length; j ++) {
            let i = 0;
            while(i < this.handles[type].length && this.handles[type]) {
                if(this.handles[type][i] == handle[j]){
                    delete this.handles[type][i];
                    this.handles[type].splice(i, 1);
                    if(this.handles[type].length == 0){
                        delete this.handles[type];
                    }
                    break;
                }
                i ++;
            }
        }
    }
}